package com.jiayou.handler

import com.jiayou.codec.ChannelDecoder
import com.jiayou.codec.ChannelEncoder
import com.jiayou.message.OnLineMessage
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.group.ChannelGroup
import io.netty.channel.socket.SocketChannel
import io.netty.handler.timeout.IdleStateHandler
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

/**
@author 李 双
@data   2020-11-19  13:18
@info
 */
@Component
class ServerChildHandler : ChannelInitializer<SocketChannel>() {  //创造一个通道测试的对象

    init {
        thread {
            while (true) {
                println("在线用户列表:")
                users.forEach(::println)
                Thread.sleep(5000)
            }
        }
    }

    @Autowired
    private lateinit var channelGroup: ChannelGroup


    var users = ConcurrentHashMap<OnLineMessage, Channel>()


    override fun initChannel(p0: SocketChannel) {
        p0.pipeline().addLast(ChannelDecoder())
        p0.pipeline().addLast(ChannelEncoder())
        p0.pipeline().addLast(IdleStateHandler(10, 10, 1000, TimeUnit.SECONDS))
        p0.pipeline().addLast(ServerIdleStateHandler(channelGroup))
        p0.pipeline().addLast(ServerMessageChannelHandler(users, channelGroup))
    }
}